<?php
/**
 * Created by PhpStorm.
 * User: boye
 * Date: 2017/3/1
 * Time: 9:23
 */

namespace app\web\controller;


use app\src\user\logic\UcenterMemberLogic;
use app\src\user\logic\UserGroupLogic;
use app\src\user\logic\MemberLogic;
use app\src\user\logic\UserMemberLogic;
use app\src\user\logic\MemberConfigLogic;
use app\src\user\logic\VUserInfoLogic;
use app\src\wallet\logic\WalletApplyLogic;
use app\src\wallet\logic\WalletHisLogicV2;
use app\src\wallet\logic\WalletLogic;
use app\src\wallet\logic\WalletOrderLogicV2;
use app\src\wallet\logic\WithdrawAccountLogicV2;
use app\src\wxpay\logic\WxaccountLogic;
use app\pc\helper\PcFunctionHelper;
use app\src\product\logic\ProductimageLogic;
use app\src\activity\logic\ActivityLogic;
use app\src\activity\logic\UserActivityLogic;
use app\weixin\Logic\WeixinLogic;
use think\Db;
use think\Exception;

class User extends Base
{

    public function iindex(){
        return $this->fetch('shop/coding');
    }

    /*
     * 二维码扫进来的入口
     */
    public function recommend(){

        $recommend_uid=input('uid');
        $recommender=(new UserMemberLogic())->getInfo(['uid'=>$recommend_uid]);

        if(!$recommender['status']||empty($recommender['info'])) $this->error('这个推荐人不存在');

        if($recommender['info']['group_id']==4) $this->error('这个推荐人没有推荐权限','index/index');
        //$recommend_sum=$recommender['info']['recommend_sum'];
        //$group_id=$recommender['info']['group_id'];
        //if($group_id==1&&$recommend_sum>200) $this->error('这个推荐人的推荐权限已用完');
        //if($group_id==2&&$recommend_sum>500) $this->error('这个推荐人的推荐权限已用完');
        //把推荐人信息预存进个人表

        if (!is_null($recommend_uid)) {
            $memberinfo=session('user_Info');
            $uid=$memberinfo['id'];
            if(empty($uid)) $this->error('读取不到您的个人信息，请重新扫描');

            $is_recommend = (new UserMemberLogic())->getInfo(['uid' => $uid]);
            if(!$is_recommend['status'] )$this->error('查询出错');
            if (!empty($is_recommend['info']['recommender'])) {
                $this->success('您已有推荐人，不可更改推荐人','index/index');
            } else {
                $recommend['uid']         = $uid;
                $recommend['recommender'] = $recommend_uid;
                $recommend['group_id'] = 4;
                $recommend['status']=0;
                $recommend['create_time']=time();
                $add_recommend            = (new UserMemberLogic())->add($recommend,'');
                if (!$add_recommend['status']) $this->error('用户添加信息出错');
            }
        }else{
            $this->error('读取不到推荐人信息，请确认二维码正确');
        }


        //增加用户的推荐数
        $or_recommend_sum=$recommender['info']['recommend_sum'];
        $add_recommend_sum=(new UserMemberLogic())->save(['uid'=>$recommend_uid],['recommend_sum'=>($or_recommend_sum+1)]);






        $this->success('预存推荐人成功了','Binding/changebinding');
    }



    /*
     * 用户个人中心
     */
    //用户个人信息，用户积分信息，用户地址信息
    public function index()
    {
        $memberinfo=$this->memberinfo;
        $this->assignTitle('我的中心');
        $this->assign('user_Info',$memberinfo);

        $uid=$memberinfo['uid'];
        $head=$memberinfo['head'];
        $this->assign('head',$head);

        $uid=$memberinfo['id'];



        return $this->fetch('user/index');
    }

    public function account(){
        $info= (new WxaccountLogic())->getInfo(['id'=>1]);
        $this->wxapi=(new WeixinLogic($info['info']['appid'], $info['info']['appsecret']));
        $signPackage = $this->wxapi -> getSignPackage();
        $jsapilist = "'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'";
        $config = "wx.config({
			    debug: false,
			    appId: '" . $signPackage["appId"] . "',
			    timestamp: '" . $signPackage["timestamp"] . "',
			    nonceStr: '" . $signPackage["nonceStr"] . "',
			    signature: '" . $signPackage["signature"] . "',
			    jsApiList: [" . $jsapilist . "]
			});";
        $this->assign('config',$config);

    }



    public function two_code(){
        $memberinfo=$this->memberinfo;
        $this->assignTitle('我的中心');
        $this->assign('user_Info',$memberinfo);
        switch ($memberinfo['roles_info']['group_info']['group_id'])
        {
            case 1:
                $level = '健康天使';
                break;
            case 2:
                $level = '健康精英';
                break;
            case 3:
                $level = '健康领袖';
                break;
            case 4:
                $level = '注册会员';
                break;
            default:
                $level = '非注册会员';
        }
        $this->assign('level',$level);
        $uid=$memberinfo['uid'];
        $code='http://dehong.8raw.com/weixin.php/weixin/user/recommend/uid/'.$uid;
        $this->assign('code',$code);

        $info= (new WxaccountLogic())->getInfo(['id'=>1]);
        $this->wxapi=(new WeixinLogic($info['info']['appid'], $info['info']['appsecret']));
        $signPackage = $this->wxapi -> getSignPackage();
        $jsapilist = "'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'";
        $config = "wx.config({
			    debug: false,
			    appId: '" . $signPackage["appId"] . "',
			    timestamp: '" . $signPackage["timestamp"] . "',
			    nonceStr: '" . $signPackage["nonceStr"] . "',
			    signature: '" . $signPackage["signature"] . "',
			    jsApiList: [" . $jsapilist . "]
			});";
        $this->assign('config',$config);

        $spread_code='http://dehong.8raw.com/weixin.php/weixin/webview/spread_code/uid/'.$uid;
        $this->assign('spread_code',$spread_code);
        return $this->fetch();
    }


    public function sign_test() {
        $info= (new WxaccountLogic())->getInfo(['id'=>1]);
        $this->wxapi=(new WeixinLogic($info['info']['appid'], $info['info']['appsecret']));
        $signPackage = $this->wxapi -> getSignPackage();
        $jsapilist = "'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo'";
        $config = "wx.config({
			    debug: false,
			    appId: '" . $signPackage["appId"] . "',
			    timestamp: '" . $signPackage["timestamp"] . "',
			    nonceStr: '" . $signPackage["nonceStr"] . "',
			    signature: '" . $signPackage["signature"] . "',
			    jsApiList: [" . $jsapilist . "]
			});";
        $this->assign('config',$config);

        var_dump($config);
    }




    public function mywallet(){
        $me=$this->memberinfo;
        $me['wallet']['points'];
        $this->assign('points', $me['wallet']['points']);
        return $this->fetch();
    }
    public function myactivity(){
        $memberinfo = $this->memberinfo;

        $result = (new UserActivityLogic())->alist(['uid'=> 183]);
        foreach ($result['info'] as $k => $v) {
            $data[$k]['act_id'] = $v['act_id'];
            $data[$k]['title'] = $v['title'];
            $data[$k]['img'] = $v['img'];
            $data[$k]['create_time'] = $v['create_time'];
        }
        if(empty($data)){
            $this->assign('alist','');
        }else{
            $this->assign('alist',$data);
        }

       // dump($data);exit;
        return $this->fetch();
    }


    public function volunteer(){
        $memberinfo = $this->memberinfo;
        $uid = $memberinfo['uid'];

        if (IS_POST) {
           // dump($_POST);exit;
            $mobile = $this->_param('tel');
            $identity=$this->_param('identity');
            $birthday=$this->_param('birthday');
            $email=$this->_param('email');
            $sex=$this->_param('sex');
            $real_photo=$this->_param('real_photo');
            $nation=$this->_param('nation');//名族
            $education=$this->_param('education');//学历
            $climate=$this->_param('climate');//政治面貌
            $residence=$this->_param('residence');//居住地
            $realname=$this->_param('realname');
            Db::startTrans();
            $entity = array(
                'mobile' => $mobile,
                'email' =>$email
            );
            $has=(new UcenterMemberLogic())->getInfo($entity);
            if(!empty($has['info'])) {
                $this->error('该手机已被绑定','');
            }
            $flag = true;
            $result =  (new UcenterMemberLogic())->save(['id' => $memberinfo['uid']],$entity);
            if(!$result['status'])  $flag = false;
            $entity = array(
                'phone_validate' => 1,
                'email_validate' => 1,
                'identity_validate'=>2

            );
            $result = (new MemberConfigLogic())->save(['uid' => $memberinfo['uid']],$entity);
            if(!$result['status'])  $flag = false;
            $entity = array(
                'idnumber' => $identity,
                'realname' => $realname,
                'sex'      => $sex,
                'birthday' =>$birthday,
                'real_photo'=>$real_photo,
                'nation'   =>$nation,
                'education'=>$education,
                'climate'=>$climate,
                'residence'=>$residence
            );
            $result =  (new MemberLogic())->save(['uid' => $memberinfo['uid']],$entity);
            if(!$result['status'])  $flag = false;

            if($flag){
                Db::commit();
                $this->success('已提交到后台等待审核','index/index');
            }else{
                Db::rollback();
                $this->error('更新失败','');
            }
        } else {
            $result = (new VUserInfoLogic())->getInfo(['id'=>$uid]);
            if($result['status']&&!empty($result['info'])){
                $result['info']['mobile']=strlen($result['info']['mobile'])==11?$result['info']['mobile']:'';
            }else{

            }

            if($result['info']['identity_validate']==1){

               $SignPackage = $this->wxapi->getSignPackage();
                $this->assign('SignPackage', $SignPackage);
             //   dump($SignPackage);exit;


                //return $this->fetch('user/jssdktest');
                return $this->fetch('user/passed');
            }
            $this->assign('userinfo', $result['info']);
            return $this->fetch();
        }

    }









    //进行手机注册，
    public function mobile_register(){
        echo 1;exit;
    }
    public function test(){
        return $this->fetch();
    }


    public function my_income(){
        $this->assignTitle('积分变动');
        $my_uid=$this->memberinfo['id'];
        $wallet_his=(new WalletHisLogicV2())->queryNoPaging(['uid'=>$my_uid]);

        $this->assign('info',$wallet_his);
        return $this->fetch();

    }






    public function my_score()
    {
        $this->assignTitle('我的积分');
        $memberinfo=$this->memberinfo;
        $this->assign('user_Info',$memberinfo);
        return $this->fetch();
    }

    //充值
    public function recharge(){
        $money=input('points');
        if(empty($money)) $this->error('充值金额错误');
        $type=input('type');
        if(empty($type)) $this->error('充值方式错误');
        $uid=$this->memberinfo['id'];
        $log_list=[
            'uid'=>$uid,
            'order_code'=>time(),
            'money'=>$money*100,
            'note'=>'充值现金',
            'status'=>'1',
            'create_time'=>time(),
            'update_time'=>time(),
            'from'=>'1',
            'pay_type'=>0,
            'pay_status'=>0,
            'pay_money'=>'0',
            'pay_code'=>'',
            'trade_no'=>''
        ];
        $log=(new WalletOrderLogicV2())->add($log_list);
        if(empty($log))$this->error('申请出错');
        $entity['order_code']='WX'.$uid.'I'.$log;
        $log_order=(new WalletOrderLogicV2())->saveByID($log,$entity);

        if($type==1){
            $this->success('订单生成成功',url('pay/jsapi',array('order_code'=>$entity['order_code'])));
        }else{
            $this->success('订单生成成功',url('Alipaytest/pay',array('out_trade_no'=>$entity['order_code'])));
        }
    }






    public function wallet_in()
    {
        $this->assignTitle('充值');
        return $this->fetch();
    }


    public function up1()
    {
        $uploadPath = substr(__DIR__, 0, strpos(__DIR__, '/application'));

        $path = $uploadPath.'/public/upload/idphoto/';
      //  dump(__DIR__);
        $file = time().$_FILES['file']['name'];
        if(!is_file($file)){
            //
        }
        if(copy($_FILES["file"]["tmp_name"],$path.$file)){
            echo json_encode(array('src'=>'http://'.$_SERVER['HTTP_HOST']."/minjian/public/upload/idphoto/".$file,'size'=>$_FILES["file"]['size'],"error"=>0));
        }else{
            echo json_encode(array("error"=>1));
        }
    }
}